package com.spring.boot.service.keys;

import org.springframework.context.annotation.Description;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis中Key值
 *
 * @author LiKun
 * @date 2021/9/10 9:03
 */
@Service
public class KeyService {

    @Resource
    private RedisTemplate redisTemplate;

    @Description("随机获取一个Key")
    public Object randomKey() {
        return redisTemplate.randomKey();
    }

    @Description("获取给定Key的类型")
    public void type(String key) {
        redisTemplate.type(key);
    }

    @Description("查看是否存在给定的Key")
    public boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

    @Description("获取给定Key的存活时间")
    public Long ttl(String key) {
        return redisTemplate.getExpire(key);
    }

    @Description("从Redis中删除给定的Key")
    public boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    @Description("一处给定Key的过期时间")
    public boolean persist(String key) {
        return redisTemplate.persist(key);
    }

    @Description("查询符合给定规则的Key")
    public Set<Object> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    @Description("重命名给定的oldKey为newKey")
    public void rename(String oldKey, String newKey) {
        // 结果等价于：删除oldKey，新增newKey
        redisTemplate.rename(oldKey, newKey);
    }

    @Description("为给定的Key设置存活时间")
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        return redisTemplate.expire(key, time, timeUnit);
    }

    @Description("当newKey不存在时重命名oldKey为newKey")
    public void renameIfAbsent(String oldKey, String newKey) {
        redisTemplate.renameIfAbsent(oldKey, newKey);
    }

}
